
import React, { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { X, Save, Plus, Trash2, Users, Truck, Wrench } from "lucide-react";

// Reusable component for editing resource arrays
const ResourceEditor = ({ title, items = [], onUpdate, fields, icon: Icon }) => {
    const safeItems = Array.isArray(items) ? items : [];

    const handleAddItem = () => {
        const newItem = fields.reduce((acc, field) => {
            acc[field.name] = field.type === 'number' ? 0 : '';
            return acc;
        }, {});
        onUpdate([...safeItems, newItem]);
    };

    const handleUpdateItem = (index, fieldName, value) => {
        const newItems = [...safeItems];
        const field = fields.find(f => f.name === fieldName);
        newItems[index][fieldName] = field.type === 'number' ? parseInt(value) || 0 : value;
        onUpdate(newItems);
    };

    const handleRemoveItem = (index) => {
        onUpdate(safeItems.filter((_, i) => i !== index));
    };

    return (
        <div className="space-y-4 p-4 border rounded-lg bg-gray-50/50">
            <h3 className="font-medium text-gray-800 flex items-center gap-2">
                {Icon && <Icon className="w-5 h-5" />}
                {title}
            </h3>
            <div className="space-y-3 max-h-96 overflow-y-auto">
                {safeItems.map((item, index) => (
                    <div key={index} className="grid grid-cols-4 gap-2 items-center p-2 bg-white rounded border">
                        {fields.map(field => (
                            <div key={field.name} className={field.name === 'specification' ? 'col-span-2' : ''}>
                                <Label htmlFor={`${field.name}-${index}`} className="text-xs sr-only">{field.label}</Label>
                                <Input
                                    id={`${field.name}-${index}`}
                                    type={field.type || 'text'}
                                    value={item[field.name] || (field.type === 'number' ? 0 : '')}
                                    onChange={(e) => handleUpdateItem(index, field.name, e.target.value)}
                                    placeholder={field.label}
                                    className="text-sm"
                                />
                            </div>
                        ))}
                        <Button
                            type="button" // Added type="button"
                            variant="ghost"
                            size="icon"
                            onClick={() => handleRemoveItem(index)}
                            className="text-red-500 hover:text-red-700 justify-self-end"
                        >
                            <Trash2 className="w-4 h-4" />
                        </Button>
                    </div>
                ))}
            </div>
            <Button
                type="button" // Added type="button"
                variant="outline"
                size="sm"
                onClick={handleAddItem}
                className="bg-white"
            >
                <Plus className="w-4 h-4 mr-2" /> 添加{title}
            </Button>
        </div>
    );
};


export default function OperationalUnitForm({ unit, onSubmit, onCancel }) {
  const [localUnit, setLocalUnit] = useState({
    name: "",
    type: "constructionUnit",
    resource_capacity: { max_concurrent_teams: "", max_projects: "" },
    personnel_resources: [],
    machinery_resources: [],
    tool_resources: [],
    contact_person: "",
    contact_phone: "",
  });

  useEffect(() => {
    if (unit) {
      setLocalUnit({
        name: unit.name || "",
        type: unit.type || "constructionUnit",
        resource_capacity: {
          max_concurrent_teams: unit.resource_capacity?.max_concurrent_teams || "",
          max_projects: unit.resource_capacity?.max_projects || ""
        },
        personnel_resources: unit.personnel_resources || [],
        machinery_resources: unit.machinery_resources || [],
        tool_resources: unit.tool_resources || [],
        contact_person: unit.contact_person || "",
        contact_phone: unit.contact_phone || "",
        id: unit.id // Preserve ID if editing an existing unit
      });
    }
  }, [unit]);

  const handleFieldChange = (field, value) => {
    setLocalUnit(prev => ({ ...prev, [field]: value }));
  };

  const handleResourceCapacityChange = (field, value) => {
    setLocalUnit(prev => ({
      ...prev,
      resource_capacity: {
        ...prev.resource_capacity,
        [field]: value
      }
    }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    // Clean up empty resource capacity fields
    const cleanedUnit = {
      ...localUnit,
      resource_capacity: {
        max_concurrent_teams: localUnit.resource_capacity.max_concurrent_teams
          ? parseInt(localUnit.resource_capacity.max_concurrent_teams)
          : undefined,
        max_projects: localUnit.resource_capacity.max_projects
          ? parseInt(localUnit.resource_capacity.max_projects)
          : undefined
      }
    };

    // Remove undefined values from resource_capacity
    Object.keys(cleanedUnit.resource_capacity).forEach(key => {
      if (cleanedUnit.resource_capacity[key] === undefined) {
        delete cleanedUnit.resource_capacity[key];
      }
    });

    // Ensure resource arrays are clean (e.g., no empty objects or zero quantities)
    cleanedUnit.personnel_resources = (cleanedUnit.personnel_resources || []).filter(r => r.trade && r.quantity > 0);
    cleanedUnit.machinery_resources = (cleanedUnit.machinery_resources || []).filter(r => r.name && r.quantity > 0);
    cleanedUnit.tool_resources = (cleanedUnit.tool_resources || []).filter(r => r.name && r.quantity > 0);

    onSubmit(cleanedUnit);
  };

  const unitTypes = [
    { value: "constructionUnit", label: "施工单位" },
    { value: "designUnit", label: "设计单位" },
    { value: "supervisionUnit", label: "监理单位" }
  ];

  const personnelFields = [
    { name: 'trade', label: '工种' },
    { name: 'quantity', label: '人数', type: 'number' },
    { name: 'skill_level', label: '技能等级' }
  ];

  const machineryFields = [
    { name: 'name', label: '机械名称' },
    { name: 'specification', label: '规格型号' },
    { name: 'quantity', label: '数量', type: 'number' }
  ];

  const toolFields = [
    { name: 'name', label: '工器具名称' },
    { name: 'specification', label: '规格型号' },
    { name: 'quantity', label: '数量', type: 'number' }
  ];

  return (
    <Card className="mb-6 shadow-lg border-green-200">
      <CardHeader className="bg-green-50">
        <CardTitle className="flex items-center justify-between">
          <span>{unit ? '编辑作业单位' : '新建作业单位'}</span>
          <Button type="button" variant="ghost" size="icon" onClick={onCancel}> {/* Added type="button" */}
            <X className="w-4 h-4" />
          </Button>
        </CardTitle>
      </CardHeader>

      <CardContent className="p-6">
        <form onSubmit={handleSubmit} className="space-y-6">
          <Tabs defaultValue="basic" className="w-full">
            <TabsList className="grid w-full grid-cols-5">
              <TabsTrigger value="basic">基本信息</TabsTrigger>
              <TabsTrigger value="capacity">总体能力</TabsTrigger>
              <TabsTrigger value="personnel">人力资源</TabsTrigger>
              <TabsTrigger value="machinery">机械设备</TabsTrigger>
              <TabsTrigger value="tools">工器具</TabsTrigger>
            </TabsList>

            <TabsContent value="basic" className="pt-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="name">单位名称 *</Label>
                  <Input
                    id="name"
                    value={localUnit.name}
                    onChange={(e) => handleFieldChange("name", e.target.value)}
                    placeholder="如：第一施工单位"
                    required
                  />
                </div>

                <div>
                  <Label htmlFor="type">单位类型 *</Label>
                  <Select
                    value={localUnit.type}
                    onValueChange={(value) => handleFieldChange("type", value)}
                  >
                    <SelectTrigger><SelectValue placeholder="选择单位类型" /></SelectTrigger>
                    <SelectContent>
                      {unitTypes.map(type => (
                        <SelectItem key={type.value} value={type.value}>{type.label}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div>
                  <Label htmlFor="contact_person">联系人</Label>
                  <Input
                    id="contact_person"
                    value={localUnit.contact_person}
                    onChange={(e) => handleFieldChange("contact_person", e.target.value)}
                    placeholder="负责人姓名"
                  />
                </div>

                <div>
                  <Label htmlFor="contact_phone">联系电话</Label>
                  <Input
                    id="contact_phone"
                    value={localUnit.contact_phone}
                    onChange={(e) => handleFieldChange("contact_phone", e.target.value)}
                    placeholder="联系电话"
                  />
                </div>
              </div>
            </TabsContent>

            <TabsContent value="capacity" className="pt-6">
              <div className="space-y-4">
                <h3 className="text-lg font-semibold text-gray-900">总体资源承载能力</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 p-4 border rounded-lg bg-gray-50/50">
                  <div>
                    <Label htmlFor="max_concurrent_teams">最大并行施工队数</Label>
                    <Input
                      id="max_concurrent_teams"
                      type="number"
                      min="1"
                      value={localUnit.resource_capacity.max_concurrent_teams}
                      onChange={(e) => handleResourceCapacityChange("max_concurrent_teams", e.target.value)}
                      placeholder="如：3"
                    />
                    <p className="text-xs text-gray-500 mt-1">同时可投入施工的队伍数量</p>
                  </div>
                  <div>
                    <Label htmlFor="max_projects">最大管理项目数</Label>
                    <Input
                      id="max_projects"
                      type="number"
                      min="1"
                      value={localUnit.resource_capacity.max_projects}
                      onChange={(e) => handleResourceCapacityChange("max_projects", e.target.value)}
                      placeholder="如：5"
                    />
                    <p className="text-xs text-gray-500 mt-1">同时可管理的项目总数</p>
                  </div>
                </div>
              </div>
            </TabsContent>

            <TabsContent value="personnel" className="pt-6">
               <ResourceEditor
                title="人力资源"
                items={localUnit.personnel_resources}
                onUpdate={(value) => handleFieldChange('personnel_resources', value)}
                fields={personnelFields}
                icon={Users}
              />
            </TabsContent>

            <TabsContent value="machinery" className="pt-6">
              <ResourceEditor
                title="机械设备"
                items={localUnit.machinery_resources}
                onUpdate={(value) => handleFieldChange('machinery_resources', value)}
                fields={machineryFields}
                icon={Truck}
              />
            </TabsContent>

            <TabsContent value="tools" className="pt-6">
               <ResourceEditor
                title="工器具"
                items={localUnit.tool_resources}
                onUpdate={(value) => handleFieldChange('tool_resources', value)}
                fields={toolFields}
                icon={Wrench}
              />
            </TabsContent>
          </Tabs>

          <div className="flex justify-end gap-3 pt-4 border-t">
            <Button type="button" variant="outline" onClick={onCancel}>
              <X className="w-4 h-4 mr-2" />
              取消
            </Button>
            <Button type="submit" className="bg-green-600 hover:bg-green-700">
              <Save className="w-4 h-4 mr-2" />
              保存单位
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}
